package com.jackrain.nea.omslocal.Dao;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.GetSqunceService;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.JsonKeyCheck;
import com.jackrain.nea.omslocal.util.PackageJsonSqlUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.Date;

/**
 * @Discription: 京东订单发货
 * Created with IntelliJ IDEA.
 * @Author wcy
 * @Date 2018/5/8 10:25:00
 */
@Slf4j
@Component
public class JingDongSendOrderDao {

    @Autowired
    private LocalLogService localLogService;

    @Autowired
    private GetSqunceService getSqunceService;

    @Autowired
    private PackageJsonSqlUtil packageJsonSqlUtil;

    @Autowired
    private PropertiesConf pconf;

    @Autowired
    private SendMqServies sendMqServies;

    public void sendOrderStart(JSONArray tempArr, String msgkey, String topic,String tag) throws ParseException {
        JingDongSendOrderDao dao = ApplicationContextHandle.getBean(JingDongSendOrderDao.class);
        System.out.println(tempArr.toJSONString());
        if (tempArr == null || tempArr.isEmpty()) {
            // 商品数据为空, 不需操作
            log.debug("京东商品数据为空, msgkey : " + msgkey);
            return;
        }
        for (Object obj : tempArr) {

            JSONObject tempObj = null;
            long  omsonlineorderid = 0;
            Long tid = 0L;
            String sellerNick = null;
            try {

                tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                omsonlineorderid = tempObj.getLong("OMSONLINEORDERID");
                tid = tempObj.getLong("TID");
                sellerNick = tempObj.getString("SELLER_NICK");
                dao.updateJdOrderOutStorage(tempObj,omsonlineorderid);

                localLogService.insertLogForJd(null,tid.toString(),topic,msgkey,sellerNick,null,0);
            }catch (Exception e){
                // 发生异常,处理
                // 获取流
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                // 逐条将错误信息以消息发送到线上发送到线上
                JSONObject errObj = new JSONObject();
                errObj.put("flag",0);
                errObj.put("platid", tempObj.getLong("TID"));
                errObj.put("sellernick", tempObj.getString("SELLER_NICK"));
                errObj.put("topic", topic);
                errObj.put("tag", tag);
                errObj.put("msgkey", msgkey);
                // 线下消费报错的主机 ip
                errObj.put("ip", NetUtils.getLocalAddress());
                // 将错误以流写出
                e.printStackTrace(pw);
                errObj.put("errmsg", sw.toString());
                errObj.put("sendtime", System.currentTimeMillis());
                try {
                    sendMqServies.sendMqObj(errObj, pconf.getProperty("ons.jdLogErrTopic"), tag);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    log.debug("京东商品发送错误信息失败");
                }
                log.debug("发货数据插入失败 : tid :" + tempObj.getLong("TID") + "msgkey : " + msgkey + sw.toString());
                // 处理异常  1.将错误信息发送到线上  2. 将错误信息保存到本地数据库
                // 插入本地错误
                localLogService.insertLogForJd(e.getMessage(),tid.toString(),topic,msgkey,sellerNick,null,1);
            }
        }
    }


    /**
     * 更新订单出库中间表表数据
     *
     * @param tempObj
     * @param orderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJdOrderOutStorage(JSONObject tempObj, long orderId) throws ParseException {
        if (tempObj!=null){
            String orderTableName = "T_OMS_ORDEROUTSTORAGE";
            synchronized (this) {
                // 校验字段
                JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
                tempObj = checkjson.checkJsonkey(tempObj, orderTableName, checkjson.getUpdatecolsmap());
            }
            tempObj.put("SyncTime",new Date(System.currentTimeMillis()));
            String params = packageJsonSqlUtil.packageUpdateCloumnName(tempObj);
            Object[] objArr =packageJsonSqlUtil.packageUpdateColumnValue(tempObj);
            String sql = "update T_OMS_OrderOutStorage set " + params + " where OMSONLINEORDERID = ?";
            QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, orderId));
        }else {
            log.error("订单发货数据为空");
        }
    }
}
